<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片式图 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 实现情况输入框，搜索功能 -->
          <!-- <el-input placeholder="请输入内容"
                    clearable
                    @clear='getUserList'
                    v-model="queryInfo.query"> -->
          <el-input placeholder="请输入内容"
                    clearable
                    v-model="queryInfo.query">
            <!-- 搜索功能 -->
            <!-- <el-button slot="append"
                       icon="el-icon-search"
                       @click='getUserList'></el-button> -->
            <el-button slot="append"
                       icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary"
                     @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList"
                border
                stripe
                style="width: 100%">
        <!-- type = index可以为表格指定列表顺序 -->
        <el-table-column type="index">
        </el-table-column>
        <el-table-column prop="username"
                         label="姓名">
        </el-table-column>
        <el-table-column prop="email"
                         label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile"
                         label="电话">
        </el-table-column>
        <el-table-column prop="role_name"
                         label="角色">
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state"
                       @change="userStateChange($event,scope.row.id)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary"
                       size="mini"
                       icon="el-icon-edit"
                       @click='showEditDialog(scope.row.id)'></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger"
                       size="mini"
                       icon="el-icon-delete"
                       @click='showDeleteDialog(scope.row.id)'></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip class="item"
                        effect="dark"
                        content="分配角色"
                        placement="top"
                        :enterable="false">
              <el-button type="warning"
                         size="mini"
                         icon="el-icon-setting"
                         @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pagenum"
                     :page-sizes="[1, 2, 5, 10]"
                     :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户"
               :visible.sync="addDialogVisible"
               width="50%"
               @close='addDialogClose'>
      <!-- 内容主体区 -->
      <el-form :model="addForm"
               :rules="addFormRules"
               ref="addFormRef"
               label-width="70px">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户"
               :visible.sync="editDialogVisible"
               width="50%"
               @close='editDialogClose'>
      <!-- 内容主体区 -->
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editFormRef"
               label-width="70px">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="editForm.username"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号"
                      prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editFormInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色"
               :visible.sync="dialogVisible"
               width="50%"
               @close="setRoleDialogClosed">
      <div>
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectedRoleId"
                     placeholder="请选择">
            <el-option v-for="item in rolesList"
                       :key="item.id"
                       :label="item.roleName"
                       :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    // 验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      // 校验邮箱的正则表达式
      const regs = /^([a-zA-Z0-9_-])+@(a-zA-Z0-9_-)+(\.a-zA-Z0-9_-)+/
      if (value.length === 0) {
        callback()
      } else {
        if (!regs.test(value)) {
          return callback(new Error('邮箱输入不合法'))
        } else {
          return callback()
        }
      }
    }
    // 验证手机号规则
    var validatePhone = (rule, value, callback) => {
      var phone = value.replace(/\s/g, '')// 去除空格
      // 校验手机号，号段主要有(不包括上网卡)：130~139、150~153，155~159，180~189、170~171、176~178。14号段为上网卡专属号段
      const regs = /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/
      if (value.length === 0) {
        callback()
      } else {
        if (!regs.test(phone)) {
          callback(new Error('手机号输入不合法'))
        } else {
          callback()
        }
      }
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页展示多少条数据
        pagesize: 2
      },
      userList: [{
        id: 25,
        type: 1,
        username: 'admin',
        email: 'adsfad@qq.com',
        mobile: '12345678',
        role_name: '超级管理员',
        mg_state: true
      }, {
        id: 35,
        type: 1,
        username: 'linken',
        email: 'asdf@qq.com',
        mobile: '278722792',
        role_name: '测试角色',
        mg_state: false
      }, {
        id: 45,
        type: 1,
        username: 'asmi',
        email: '111111@qq.com',
        mobile: '1871991',
        role_name: '主管',
        mg_state: true
      }, {
        id: 55,
        type: 1,
        username: 'hhihdi',
        email: 'dihdidhid@qq.com',
        mobile: '999999',
        role_name: 'test',
        mg_state: false
      }],
      total: 4,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 添加用户表单对象
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单校验规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }

        ]
      },
      // 添加用户表单校验规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
          // { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }

        ]
      },
      // 查询到的用户信息对象
      editForm: {},
      dialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色数据
      rolesList: [{
        id: 1,
        roleName: '张三'
      }, {
        id: 2,
        roleName: '李四'
      }],
      // 已选择的角色id
      selectedRoleId: ''

    }
  },
  created () {
    // 页面挂载之后发送请求获取用户列表数据
    // that.getUserList()
  },
  methods: {
    async getUserList () {
      const that = this
      // 发送get请求时，请求参数要用params
      const { data: res } = await that.$http.get('users', { params: that.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听pagesize改变的事件
    handleSizeChange (newSize) {
      // console.log(`每页 ${newSize} 条`);
      this.queryInfo.pagesize = newSize
      // 暂时没有接口，需要调用API才可以实现每页展示数据的改变
      // this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newPage) {
      // console.log(`当前页: ${newPage}`);
      this.queryInfo.pagenum = newPage
      // this.getUserList()
    },
    // 修改用户状态put请求
    async userStateChange (userInfo, userId) {
      const that = this
      console.log(userInfo, userId)
      // 解构函数：将data重命名为res
      /* const { data: res } = await that.$http.put(`user/${userInfo.id}/state/${userInfo.type}`)
      if (res.meta.state !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        that$message.error('更新用户状态失败')
      }
      that.$message.success('更新用户状态成功！') */
      for (let i = 0; i < that.userList.length; i++) {
        if (that.userList[i].id === userId) {
          that.userList[i].mg_state = userInfo
          that.$message.success('更新用户状态成功！')
        }
      }
    },
    // 监听添加用户对话框的关闭事件
    addDialogClose () {
      const that = this
      that.$refs.addFormRef.resetFields()
    },
    // 确定添加用户事件
    addUser () {
      const that = this
      that.$refs.addFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        // 可以发起添加用户的网络请求
        const { data: res } = await that.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          return that.$message.error('添加用户失败')
        }
        that.$message.success('添加用户成功')
        // 隐藏添加用户对话框
        that.addDialogVisible = false
        // 重新获取用户列表
        that.getUserList()
      })
    },
    // 展示修改用户信息对话框
    async showEditDialog (userId) {
      const that = this
      console.log(userId)
      that.editDialogVisible = true
      /* const { data: res } = await that.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return that.$message.error('查询用户信息失败')
      }
      that.editForm = res.data */
      const userList = that.userList
      for (let i = 0; i < userList.length; i++) {
        if (userId === userList[i].id) {
          that.editForm = {
            username: userList[i].username,
            mobile: userList[i].mobile,
            email: userList[i].email
          }
        }
      }
    },
    // 监听修改用户对话框的关闭事件
    editDialogClose () {
      const that = this
      that.refs.editFormRef.resetFields()
    },
    // 确定修改用户信息事件
    editFormInfo () {
      const that = this
      that.$refs.editFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        // 可以发起编辑用户信息提交的网络请求
        const { data: res } = await that.$http.put('users' + that.editForm.id, { email: that.editForm.email, mobile: that.editForm.mobile })
        if (res.meta.status !== 200) {
          return that.$message.error('修改用户信息失败')
        }
        that.$message.success('修改用户信息成功')
        // 隐藏修改用户对话框
        that.editDialogVisible = false
        // 重新获取用户列表
        // that.getUserList()
      })
    },
    // 删除用户提示框显示
    async showDeleteDialog (userId) {
      const that = this
      // 询问用户是否删除数据,res是一个promise，可以用async和await修饰
      const res = await that.$confirm('此操作将永久删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(res)
      // 如果用户点击的是确定按钮，返回的是confirm;
      // 如果用户点击的是取消按钮，返回cancel
      if (res !== 'confirm') {
        return that.$message.info('已取消删除')
      }
      // 发起删除用户的网络请求
      const { data: result } = await that.$http.delete('users' + userId)
      if (result.meta.status !== 200) {
        return that.$message.error('删除用户失败')
      }
      that.$message.success('删除用户成功')
      // 隐藏修改用户对话框
      that.editDialogVisible = false
      // 重新获取用户列表
      // that.getUserList()
    },
    async setRole (role) {
      console.log(role)
      // 在展示对话框之前，获取所有角色列表
      // const { data: res } = await this.$http.get('roles')
      // if (res.meta.status !== 200) {
      //   return this.$message.error('获取角色失败')
      // }
      // this.rolesList = res.data
      this.userInfo = role
      this.dialogVisible = true
    },
    // 点击按钮分配角色
    async saveRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      // const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      // if (res.meta.status !== 200) {
      //   return this.$message.error('更新角色失败')
      // }
      this.$message.success('分配角色成功')
      this.dialogVisible = false
    },
    setRoleDialogClosed () {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>
<style scope>
</style>
